<script setup lang="ts">
import {onMounted, toRaw, watchEffect} from 'vue';
import { walletStore } from "@/store";
import { useChainId, useAccount, useDisconnect, useSignMessage, useConnect, Connector  } from '@wagmi/vue';
import { bscTestnet } from '@wagmi/vue/chains';

const wallet_store = walletStore()
const { connectors, connect } = useConnect();
const { address, status, isConnected } = useAccount();
const rawConnector = toRaw(connectors[0]) as Connector;
const { signMessage } = useSignMessage()
const { disconnect } = useDisconnect();

const chainId = useChainId();
wallet_store.chainId = chainId.value
wallet_store.address = address.value as string
wallet_store.isConnected = isConnected.value
wallet_store.status = status.value
// 监听账号变化
watchEffect(() => {
  if (isConnected.value && address.value) {
    // 用变更后的地址和之前存储的地址比较，有变化表示账号变更
    if(address.value != wallet_store.address && wallet_store.address) {
      console.log('账号变更', address.value, wallet_store.address);
      // do something
    }
    // 更新wallet_store
    wallet_store.address = address.value;
    wallet_store.isConnected = isConnected.value
    wallet_store.chainId = chainId.value
    wallet_store.status = status.value
  }
  // 监听状态变化
  if(status.value != wallet_store.status) {
    wallet_store.status = status.value
  }
  // 监听网络
  if(chainId.value != wallet_store.chainId) {
    wallet_store.chainId = chainId.value
  }
  // 监听是否连接
  if(isConnected.value != wallet_store.isConnected) {
    wallet_store.isConnected = isConnected.value
  }
});

// 连接钱包函数
const connectWallet = (callback: () => void) => {
  try {
    connect({
      connector: rawConnector,
      chainId: bscTestnet.id,
    }, {
      onSuccess: () => {
        console.log('连接成功')
        callback()
      },
    });
  } catch (e) {
    console.log('连接钱包失败:', e);
  }
};
wallet_store.connectWallet = connectWallet

// 断开连接函数
const disconnectWallet = async () => {
  try {
    disconnect();
    console.log('断开连接成功')
    // 更新wallet_store
    wallet_store.message = '';
  } catch (e) {
    console.log('断开连接失败:', e);
  }
};
wallet_store.disconnectWallet = disconnectWallet

// 签名函数
const SignMessage = async (message: string = 'hello world', callback: () => void): Promise<void> => {
   signMessage({message}, {
    onSuccess: (data) => {
      wallet_store.message = data
      callback()
    },
    onError: (error) => {
      console.log('签名失败:', error);
      wallet_store.disconnectWallet()
    }
  })
};
wallet_store.SignMessage = SignMessage

const callback_f = async () => {
   wallet_store.SignMessage('hello world', signSuccess)
}
const signSuccess = async () => {
  console.log('签名成功', wallet_store.message);
}

// 组件挂载时尝试自动连接
onMounted(() => {
  // if (!isConnected.value) {
  //   connectWallet();
  // }
});
</script>


<template>
  <div class="col_box">
    <span>状态：{{ wallet_store.status }}</span>
    <span>网络：{{ wallet_store.chainId }}</span>
    <span>地址：{{ wallet_store.address }}</span>
    <button v-if="!wallet_store.isConnected" @click="wallet_store.connectWallet(callback_f)">连接</button>
    <button v-else @click="wallet_store.disconnectWallet">断开</button>
    <code>{{ wallet_store.message }}</code>
  </div>
</template>

<style lang="scss" scoped>
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(20px);
  opacity: 0;
}
</style>
